package cn.lyq.card.ui.agent

import android.content.Context
import android.content.Intent
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import cn.lyq.card.R
import cn.lyq.card.base.BaseActivity
import cn.lyq.card.data.model.AgentInfo
import cn.lyq.card.data.model.PageInfo
import cn.lyq.card.data.src.Result
import cn.lyq.card.data.src.Status
import cn.lyq.card.ui.common.KeyAdapter
import cn.lyq.card.utils.setClick
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.ToastUtils
import kotlinx.android.synthetic.main.act_agent_list.*


class AgentListActivity : BaseActivity() {


    private val type by lazy {
        intent.getIntExtra(KEY_TYPE, 0)
    }
    private val date by lazy {
        intent.getStringExtra(KEY_DATE) ?: ""
    }
    private val mModel by lazy {
        getVM(AgentListVM::class.java)
    }
    private val mAdapter by lazy {
        KeyAdapter()
    }
    private var key = ""
    private val mInfoList = mutableListOf<AgentInfo>()
    private val page = PageInfo()

    companion object {

        private const val KEY_TYPE = "TYPE"
        private const val KEY_DATE = "DATE"

        /**
         * 0日、1月、2全部
         */
        @JvmStatic
        fun start(context: Context, type: Int, date: String) {
            val starter = Intent(context, AgentListActivity::class.java)
                .putExtra(KEY_TYPE, type)
                .putExtra(KEY_DATE, date)
            context.startActivity(starter)
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.act_agent_list
    }

    override fun initView() {
        super.initView()
        setMyTitle(if (type == 2) R.string.str_agent_amount else R.string.str_agent_new)

        rv.layoutManager = LinearLayoutManager(this)
        rv.adapter = mAdapter
        mAdapter.setEmptyView(R.layout.layout_empty)
        mAdapter.loadMoreModule.apply {
            checkDisableLoadMoreIfNotFullPage()
            preLoadNumber = 2
            setOnLoadMoreListener {
                getData(page.loadMore())
            }
        }
        mAdapter.setOnItemClickListener { _, _, position ->
            AgentDetailActivity.start(this, type, mInfoList[position].id)
        }
    }

    private fun getData(pageNum: Int) {
        mModel.getData(pageNum, key, date).observe(this, Observer {
            when (it?.status) {
                Status.SUCCESS -> {
                    loadSuccess(it)
                }
                Status.ERROR -> {
                    page.fail()
                    refreshLayout.isRefreshing = false
                    mAdapter.loadMoreModule.loadMoreFail()
                    ToastUtils.showShort(it.message.getMsg())
                }
                Status.LOADING ->{
                    if (page.isRefresh() && !refreshLayout.isRefreshing){
                        refreshLayout.isRefreshing = true
                    }
                }
            }
        })
    }

    private fun loadSuccess(it: Result<MutableList<AgentInfo>>) {
        val temp = mutableListOf<String>()
        it.data?.forEach { info ->
            temp.add(info.agentName ?: "")
        }
        if (page.isRefresh()) {
            mInfoList.clear()
            mAdapter.key = key
            mAdapter.setList(temp)
        } else {
            mAdapter.addData(temp)
        }
        mInfoList.addAll(it.requireData())
        page.success()
        if (temp.size < mModel.pageSize) {
            mAdapter.loadMoreModule.loadMoreEnd()
        } else {
            mAdapter.loadMoreModule.loadMoreComplete()
        }
        refreshLayout.isRefreshing = false
    }

    override fun initListener() {
        super.initListener()
        refreshLayout.setOnRefreshListener {
            key = etSearch.text.toString()
            getData(page.refresh())
        }
        tvSearch.setClick {
            key = etSearch.text.toString()
            KeyboardUtils.hideSoftInput(etSearch)
            getData(page.refresh())
        }
    }

    override fun initObserver() {
        super.initObserver()
        mModel.type = type
        getData(page.refresh())
    }
}